// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import VueResource from 'vue-resource'
import App from './App'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条 样式
import 'element-ui/lib/theme-default/index.css'
import {getToken} from './utils/auth'
import axios from 'axios'
import directives from './directives'
import {
  Table,
  TableColumn,
  Message,
  Pagination,
  Button,
  Form,
  FormItem,
  Input,
  Loading,
  MessageBox,
  Notification,
  Row,
  Col,
  Upload,
  Dialog,
  Tabs,
  TabPane,
  Tag,
  Select,
  Option,
  Popover
} from 'element-ui'
Vue.use(Table)
Vue.use(TableColumn)
Vue.use(Pagination)
Vue.use(Button)
Vue.use(Form)
Vue.use(Input)
Vue.use(Loading.directive)
Vue.use(FormItem)
Vue.use(Row)
Vue.use(Col)
Vue.use(Upload)
Vue.use(Dialog)
Vue.use(Tabs)
Vue.use(TabPane)
Vue.use(Tag)
Vue.use(Select)
Vue.use(Option)
Vue.use(Popover)
Vue.directive('heightEqWidth', directives.heightEqWidth)
Vue.directive('iscroll', directives.iscroll)
Vue.prototype.$loading = Loading.service
Vue.prototype.$msgbox = MessageBox
Vue.prototype.$alert = MessageBox.alert
Vue.prototype.$confirm = MessageBox.confirm
Vue.prototype.$prompt = MessageBox.prompt
Vue.prototype.$notify = Notification
Vue.prototype.$message = Message


// axios.interceptors.request.use(function (config) {
//   // Do something before request is sent
//
//   config.headers['self-header']='yangxu';
//
//   return config;
//
// }, function (error) {
//   // Do something with request error
//   return Promise.reject(error);
// });





Vue.prototype.$http = axios
Vue.config.productionTip = false
Vue.use(VueResource)
const whiteList = ['LoginPage', 'Error404', 'Error401', 'Dashboard']// 不重定向白名单

Vue.prototype.trim = str => str.replace(/(^\s*)|(\s*$)/g,'');

Vue.prototype.$trim = str => str.replace(/(^\s*)|(\s*$)/g,'');

function hasPermission (permissions, route) {
  if (route.meta && route.meta.permission) {
    return permissions.indexOf(route.meta.permission) !== -1
  } else {
    return true
  }
}

router.beforeEach((to, from, next) => {

  NProgress.start() // 开启Progress

  const token = getToken()

  if (token) {

    Vue.http.headers.common['Authorization'] = `Bearer ${token}`

    //当从登陆页面进入到主页的时候
    if (to.name === 'LoginPage') {
      next('/')
    } else {
      //在主页里面的时候，开始检查权限
      if (store.getters.permissions.length === 0) {

        store.dispatch('getMyProfile',token).then(response => {

          const permissions = store.getters.permissions;

          store.dispatch('GenerateRoutes', { permissions }).then(() => {
            // 生成可访问的路由表
            router.addRoutes(store.getters.addRouters)
            // 动态添加可访问路由表
            next({ ...to }) // hack方法 确保addRoutes已完成

          })
        }, response => {

          Message.error(response.data.message)

          NProgress.done()

          store.dispatch('loginOut').then(() => {

            next({ path: '/login' })

          }, () => {

            next({ path: '/login' })

          })
        })
      } else {
        if (hasPermission(store.getters.permissions, to)) {
          next()
        } else {
          next({ path: '/401', query: { noGoBack: true } })
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.name) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next('/login') // 否则全部重定向到登录页
      NProgress.done() // 在hash模式下 改变手动改变hash 重定向回来 不会触发afterEach 暂时hack方案 ps：history模式下无问题，可删除该行！
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
});
